#!/bin/bash
source /Users/frontrow/atvMod_com/scripts/common.vars

### This script will download install, unpack and install the basic packages...

# DO PRE-INSTALL OPERATIONS #------------------------------------------------
OPERATION="basic-packages"
echo "Preparing Basic Packages..." > $TMP_LOG; $LOGGER $OPERATION

# Get into the install dir
mkdir -p $PACKAGES_DIR 2> $TMP_LOG; $LOGGER $OPERATION
cd $PACKAGES_DIR 2> $TMP_LOG; $LOGGER $OPERATION

# Get the newest list of packages
wget -q $TOP_URL/$PROJECT_VERSION/$HASH/packages.xml 2> $TMP_LOG; $LOGGER $OPERATION

# Go trhough all the items in packages_basic.xml
for tag in NAME URL; do
    OUT=`grep  $tag packages.xml | tr -d '\t' | sed 's/^<.*>\([^<].*\)<.*>$/\1/' `
    eval ${tag}=`echo -ne \""${OUT}"\"`
done

# Make arrays
packageName_ARRAY=( `echo ${NAME}` )
packageUrl_ARRAY=( `echo ${URL}` )

echo "Done." > $TMP_LOG; $LOGGER $OPERATION
unset OPERATION
#----------------------------------------------------------------------------

# INSTALL PACKAGES #---------------------------------------------------------
i=0
for package in ${packageName_ARRAY[@]}; do
    
    OPERATION="${packageName_ARRAY[$i]}"
    
    # Download
    echo "Downloading ${packageName_ARRAY[$i]}..." > $TMP_LOG; $LOGGER $OPERATION
    wget -q $TOP_URL/$PROJECT_VERSION/$HASH/${packageUrl_ARRAY[$i]} 2> $TMP_LOG; $LOGGER $OPERATION
    echo "Done." > $TMP_LOG; $LOGGER $OPERATION
    
    # Unpack
    echo "Unpacking ${packageName_ARRAY[$i]}..." > $TMP_LOG; $LOGGER $OPERATION
    rar x ${packageUrl_ARRAY[$i]} 2> $TMP_LOG; $LOGGER $OPERATION
    echo "Done." > $TMP_LOG; $LOGGER $OPERATION
    
    # Install
    #echo "Running ${packageName_ARRAY[$i]} installer..." > $TMP_LOG; $LOGGER $OPERATION
    cd ${packageName_ARRAY[$i]} 2> $TMP_LOG; $LOGGER $OPERATION
    sudo ./install.sh
    cd .. 2> $TMP_LOG; $LOGGER $OPERATION
    #sudo rm -rf  ${packageName_ARRAY[$i]} ${packageName_ARRAY[$i]}.rar 2> $TMP_LOG; $LOGGER $OPERATION
    #echo "Done." > $TMP_LOG; $LOGGER $OPERATION

    # Create receipt
    touch /Users/frontrow/atvpatch/receipts/${packageName_ARRAY[$i]}

    # Clean up
    sudo rm -rf ${packageUrl_ARRAY[$i]}
    sudo rm -rf ${packageName_ARRAY[$i]}

    # Do the next one
    unset OPERATION
    i=$[$i+1]

done

# Clean up
cd /Users/frontrow
sudo rm -rf $PACKAGES_DIR
